package com.example.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.crm.entity.SalesTeam;
import com.example.crm.entity.TeamMember;
import com.example.crm.entity.User;
import com.example.crm.mapper.SalesTeamMapper;
import com.example.crm.mapper.TeamMemberMapper;
import com.example.crm.mapper.UserMapper;
import com.example.crm.service.SalesTeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 销售团队服务实现类
 */
@Service
public class SalesTeamServiceImpl extends ServiceImpl<SalesTeamMapper, SalesTeam> implements SalesTeamService {

    @Autowired
    private TeamMemberMapper teamMemberMapper;
    
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<SalesTeam> listTeams() {
        List<SalesTeam> teams = list();
        
        // 查询团队负责人
        teams.forEach(team -> {
            if (team.getLeaderId() != null) {
                User leader = userMapper.selectById(team.getLeaderId());
                team.setLeader(leader);
            }
        });
        
        return teams;
    }

    @Override
    public SalesTeam getTeamDetail(Long id) {
        SalesTeam team = getById(id);
        if (team != null) {
            // 查询团队负责人
            if (team.getLeaderId() != null) {
                User leader = userMapper.selectById(team.getLeaderId());
                team.setLeader(leader);
            }
            
            // 查询团队成员
            List<TeamMember> members = teamMemberMapper.selectMembersByTeamId(id);
            team.setMembers(members);
        }
        return team;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addTeam(SalesTeam team, List<TeamMember> members) {
        // 保存团队
        boolean saved = save(team);
        
        if (saved && members != null && !members.isEmpty()) {
            // 设置团队ID
            members.forEach(member -> {
                member.setTeamId(team.getId());
                member.setJoinTime(LocalDateTime.now());
            });
            
            // 批量保存成员
            for (TeamMember member : members) {
                teamMemberMapper.insert(member);
            }
        }
        
        return saved;
    }

    @Override
    public boolean updateTeam(SalesTeam team) {
        return updateById(team);
    }

    @Override
    public List<SalesTeam> listUserTeams(Long userId) {
        // 查询用户所属的团队ID列表
        List<Long> teamIds = teamMemberMapper.selectTeamIdsByUserId(userId);
        if (teamIds.isEmpty()) {
            return new ArrayList<>();
        }
        
        // 查询团队信息
        List<SalesTeam> teams = listByIds(teamIds);
        
        // 查询团队负责人
        teams.forEach(team -> {
            if (team.getLeaderId() != null) {
                User leader = userMapper.selectById(team.getLeaderId());
                team.setLeader(leader);
            }
        });
        
        return teams;
    }

    @Override
    public List<TeamMember> listTeamMembers(Long teamId) {
        return teamMemberMapper.selectMembersByTeamId(teamId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addTeamMembers(Long teamId, List<Long> userIds, String role) {
        List<TeamMember> members = userIds.stream().map(userId -> {
            TeamMember member = new TeamMember();
            member.setTeamId(teamId);
            member.setUserId(userId);
            member.setRole(role);
            member.setJoinTime(LocalDateTime.now());
            return member;
        }).collect(Collectors.toList());
        
        // 批量保存成员
        for (TeamMember member : members) {
            teamMemberMapper.insert(member);
        }
        
        return true;
    }

    @Override
    public boolean removeTeamMember(Long teamId, Long userId) {
        LambdaQueryWrapper<TeamMember> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TeamMember::getTeamId, teamId)
                    .eq(TeamMember::getUserId, userId);
        
        return teamMemberMapper.delete(queryWrapper) > 0;
    }

    @Override
    public boolean updateTeamMemberRole(Long teamId, Long userId, String role) {
        LambdaUpdateWrapper<TeamMember> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(TeamMember::getTeamId, teamId)
                     .eq(TeamMember::getUserId, userId)
                     .set(TeamMember::getRole, role);
        
        return teamMemberMapper.update(null, updateWrapper) > 0;
    }
} 